package com.longge;

public class Tree2str {

    StringBuilder sb = new StringBuilder();
    public String tree2str(TreeNode root) {

        dfs(root);
        return sb.toString();
    }

    private void dfs(TreeNode root) {
        if (root == null) return;
        sb.append(root.val);
        if (root.left==null&&root.right!=null){
            sb.append("()");
            sb.append("(");
            dfs(root.right);
            sb.append(")");

        }
        if (root.left!=null&&root.right==null){
            sb.append("(");
            dfs(root.left);
            sb.append(")");
        }
        if (root.right!=null&&root.left!=null){
            sb.append("(");

            dfs(root.left);
            sb.append(")(");

            dfs(root.right);
            sb.append(")");

        }
    }
}
